package com.seek.quartz;

import com.seek.util.DateUtil;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;

import com.lianlianpay.PaymentApi;
import com.seek.model.entity.TCustomerCard;
import com.seek.model.entity.TLoan;
import com.seek.service.CustomerCardService;
import com.seek.service.LoanService;
import com.seek.util.MapUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LianPayQuartz {

  private static final Logger logger = LoggerFactory.getLogger(LianPayQuartz.class);

  @Resource
  private LoanService loanService;
  @Resource
  private CustomerCardService customerCardService;
  private static String flag = "S";// S:代表可执行，R:代表运行中，不可执行

  //	private Map<String, Object> map = MapUtil.getIstance();
  public void lianlianPayMent() {
    synchronized (flag) {
      try {
        if (StringUtils.equals(flag, "S")) {
          logger.info("开始执行放款任务......");
          flag = "R";
          // 执行查询，调用
          String sql = "select * from t_loan where loan_status= ? and executionstatus = 0";
          List<TLoan> ds = loanService.findBySql(sql, new Object[]{2});
          if (CollectionUtils.isNotEmpty(ds)) {
            for (TLoan t : ds) {
              // 根据客户号查询用户银行卡绑定情况
							List<TCustomerCard> cards = customerCardService.findBySql(
                  "select * from t_customer_card where customer_id=? and audit_status=? and history=?",
									new Object[] { t.getCustomerId(), 1, 0 });
							if (CollectionUtils.isNotEmpty(cards)) {
								TCustomerCard card = cards.get(0);
								t.setBankNo(card.getCardNumber());
								t.setAccountName(card.getBankName());
								t.setBankName(card.getBankName());
								PaymentApi payApi = new PaymentApi();
								payApi.lianPayMent(t);
							} 
//              payMock(t);
            }
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        flag = "S";
      }
    }

  }

  /**
   * 自动放款mock测试
   */
//  private void payMock(TLoan loan) {
//    try {
//      Date start = DateUtil
//          .getDateByString(DateUtil.dateFormat(new Date(), DateUtil.DATE_FORMAT_YMD),
//              DateUtil.DATE_FORMAT_YMD);
//
//      Date end = DateUtil.dateAdd(DateUtil.DATE_INTERVAL_DAY, start, 7);
//      end = DateUtil.dateAdd(DateUtil.DATE_INTERVAL_SECOND, end, -1);
//
//      loanService.executeUpdate(
//          "update t_loan set loan_status = ? ,down_type= ? , down_remark = ? , start_time=?, end_time = ? ,down_time=now() where id =?",
//          new Object[]{3, 1, "放款成功!",start,end, loan.getId()});
//    } catch (Exception e) {
//      e.printStackTrace();
//    }
//
//  }
}
